package com.wjj.sixinone.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

import com.alibaba.fastjson.JSON;
import com.wjj.sixinone.common.enums.RedisConstantEnum;
import com.wjj.sixinone.common.pojo.vo.ValidateCodeVo;
import com.wjj.sixinone.common.util.Result;
import com.wjj.sixinone.service.MailService;
import com.wjj.sixinone.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    static String codeKey;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Autowired
    private MailService mailService;

    @Override
    public Result generateCode() {

        // 使用hutool工具包中的工具类生成图片验证码
        //参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        String codeValue = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();

        // 生成uuid作为图片验证码的key
         codeKey = UUID.randomUUID().toString().replace("-", "");


        redisTemplate.opsForValue().set(RedisConstantEnum.USER_VERIFY_CODE.getKey() + codeKey ,
                codeValue , 5 , TimeUnit.MINUTES);

        // 构建响应结果数据
        ValidateCodeVo validateCodeVo = new ValidateCodeVo() ;
        validateCodeVo.setCodeKey(codeKey);
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);

        // 返回数据
        return Result.ok().put("data",validateCodeVo);
    }

    @Override
    public Result getEmailCode(String email) {
        return mailService.sendMail(email);
    }
}
